package com.onekbase.demo.thead;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        new Thread(new WaitThread(lock,condition),"Thread1").start();
        new Thread(new WaitThread(lock,condition),"Thread2").start();

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName()+"开始执行……");
                condition.signalAll(); // 这里只能用All
                for(int i=0;i<3;i++){
                    System.out.println(Thread.currentThread().getName()+"执行中……");
                    Thread.sleep(1000);
                }
                System.out.println(Thread.currentThread().getName()+"任务完成……");
            } catch (InterruptedException e){
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        },"Thread3").start();

        LockSupport.park();
    }

    static class WaitThread implements Runnable{
        ReentrantLock lock = null;
        Condition condition = null;

        public WaitThread(ReentrantLock lock, Condition condition) {
            this.lock = lock;
            this.condition = condition;
        }

        @Override
        public void run() {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName()+"开始执行……");
                condition.await();
                for(int i=0;i<3;i++){
                    System.out.println(Thread.currentThread().getName()+"执行中……");
                    Thread.sleep(1000);
                }
                System.out.println(Thread.currentThread().getName()+"任务完成……");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
}
